package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.cart.api.service.RemoteCartService;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.domain.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.domain.ProductSku;
import com.spzx.product.api.service.RemoteProductSkuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 订单Service业务层处理
 *
 * @author atguigu
 * @date 2024-11-04
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService
{
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RemoteProductSkuService remoteProductSkuService;

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo)
    {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        LambdaQueryWrapper<OrderItem> queryWrapper =
                new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(queryWrapper);
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    /**
     * 立即购买
     * @param skuId
     * @return
     */
    @Override
    public TradeVo buy(Long skuId) {
        //设置返回的对象
        TradeVo tradeVo = new TradeVo();
        //远程调用获取productSku信息给orderItem设置值
        R<ProductSku> productSkuById = remoteProductSkuService.getProductSkuById(skuId,SecurityConstants.INNER);
        if (R.FAIL == productSkuById.getCode()){
            throw new ServiceException("远程调用获取sku信息失败");
        }
        ProductSku productSku = productSkuById.getData();
        //给OrderItem设置值
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuNum(1);
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setThumbImg(productSku.getThumbImg());
        //将orderItem放到集合中
        ArrayList<OrderItem> orderItems = new ArrayList<>();
        orderItems.add(orderItem);

        //给tradeVo设置属性值
        tradeVo.setOrderItemList(orderItems);
        tradeVo.setTotalAmount(productSku.getSalePrice());
        tradeVo.setTradeNo(UUID.randomUUID().toString().replace("-",""));
        tradeVo.setIsBuy(true);

        return tradeVo;
    }

    /**
     * 购物车去结算
     * @return
     */
    @Override
    public TradeVo trade() {
        //获取用户Id
        Long userId = SecurityUtils.getUserId();
        //远程调用获取已经选中的购物项
        R<List<CartInfo>> checkedCartInfo = remoteCartService.getCheckedCartInfo(userId, SecurityConstants.INNER);
        if (R.FAIL == checkedCartInfo.getCode()){
            throw new ServiceException("远程调用购物车获取已经选中的购物项失败");
        }
        List<CartInfo> checkedCartInfoData = checkedCartInfo.getData();

        //创建返回的对象
        TradeVo tradeVo = new TradeVo();

        //验空
        if (!CollectionUtils.isEmpty(checkedCartInfoData)){
            //将选中的购物项目转成OrderItem集合
            List<OrderItem> orderItemList = checkedCartInfoData.stream().map(cartInfo -> {
                //设置总金额
                BigDecimal totalAmount = tradeVo.getTotalAmount();
                //创建OrderItem对象
                OrderItem orderItem = new OrderItem();
                BeanUtils.copyProperties(cartInfo, orderItem);
                //获取购物项目的数量并转换为bigDecimal类型
                BigDecimal skuNum = new BigDecimal(orderItem.getSkuNum());
                //计算总金额
                totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(skuNum));
                //设置总金额
                tradeVo.setTotalAmount(totalAmount);
                return orderItem;
            }).toList();
            //给tradeVo设置属性值
            tradeVo.setOrderItemList(orderItemList);

            //使用uuid随机生成一个字符串作为交易号
            String tradeNo = UUID.randomUUID().toString().replace("-", "");
            //设置交易号
            tradeVo.setTradeNo(tradeNo);
        }

        return tradeVo;
    }

}
